﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Actya.Web.Infrastructure.ElFinderConnector.Responses;
using Actya.Web.Infrastructure.ElFinderConnector.Utils;

namespace Actya.Web.Infrastructure.ElFinderConnector.Commands
{
	public class Upload : ICommand
	{
		public string Current { get; set; }

		public System.Web.HttpFileCollectionBase Files { get; set; }

		public Upload(string current, System.Web.HttpFileCollectionBase files)
		{
			this.Current = current;
			this.Files = files;
		}

		#region ICommand Members

		public Response Execute()
		{
			var path = DirectoryUtils.GetRelativePathByHash(Current);



			IList<string> select = new List<string>();

			var error = string.Empty;

			for (var i = 0; i < Files.Count; i++)
			{
				var file = Files[i];
				if (file.ContentLength < 1)
					continue;

				var nameArr = file.FileName.Split(".".ToCharArray());
				var ext = String.Empty;
				if (nameArr.Length > 1)
				{
					ext = nameArr[nameArr.Length -1].ToLower();
				}
				var mime = file.ContentType;

				// We should check if MIME-type is allowed, but we can't relay on the browser to send the right one.
  				// Let's only check extensions for now.
				var allowedExtensions = Configuration.Configuration.AllowedMimeTypes.SelectMany(mt => mt.Value).Distinct().ToArray();
				var filePath = Path.Combine(path, file.FileName);
				if ((! Configuration.Configuration.DisabledMimeTypes.Contains(mime)) && allowedExtensions.Contains(ext))
				{
					file.SaveAs(filePath);
					FileUtils.RemoveThumbFor(filePath);
				}
				else
				{
					error += string.Format("{0} type is not allowed for upload.", file.FileName);
				}
				select.Add(filePath.Hash());
			}

			var response = new ActionCompletedResponse();

			var folder = new Folder(path);

			response.cwd = folder.Cwd;

			response.cdc = folder.Contents;

			response.select = select;

			response.error = error;

			//response.tree = folder.Tree;

			return response;
		}

		#endregion
	}
}
